import { type NextRequest, NextResponse } from "next/server"
import { getDb, createUser } from "@/lib/db-sqlite"

// 获取所有用户
export async function GET(request: NextRequest) {
  try {
    const db = getDb()

    const users = db
      .prepare(`
        SELECT id, name, role, created_at FROM users
        ORDER BY created_at DESC
      `)
      .all()

    return NextResponse.json({ users })
  } catch (error: any) {
    console.error("Error fetching users:", error)
    return NextResponse.json({ error: error.message || "Failed to fetch users" }, { status: 500 })
  }
}

// 创建新用户
export async function POST(request: NextRequest) {
  try {
    const { name, password, role } = await request.json()

    if (!name || !password) {
      return NextResponse.json({ error: "Name and password are required" }, { status: 400 })
    }

    const user = createUser(name, password, role || "user")

    if (!user) {
      return NextResponse.json({ error: "Failed to create user" }, { status: 500 })
    }

    return NextResponse.json({ user })
  } catch (error: any) {
    console.error("Error creating user:", error)
    return NextResponse.json({ error: error.message || "Failed to create user" }, { status: 500 })
  }
}
